import 'package:flutter/material.dart';
import 'package:flutter_base/base/controller/base_controller.dart';
import 'package:flutter_base/config/app_routes.dart';
import 'package:flutter_base/pages/search/model/search_history.dart';
import 'package:get/get.dart';

class SearchLogic extends BaseController {
  // 搜索控制器
  final TextEditingController searchController = TextEditingController();

  // Search Test Questions
  FocusNode searchFocusNode = FocusNode();

  // 搜索历史
  RxList<String> searchHistory = <String>[].obs;

  // 是否显示清除按钮
  RxBool showClear = false.obs;

  @override
  void onInit() {
    super.onInit();

    // 监听输入框变化，控制清除按钮显示
    searchController.addListener(() {
      showClear.value = searchController.text.isNotEmpty;
    });
  }

  @override
  void onReady() {
    super.onReady();
    loadSearchHistory();
  }

  @override
  void onClose() {
    searchController.dispose();
    // searchFocusNode.di
    super.onClose();
  }

  // 加载搜索历史
  Future<void> loadSearchHistory() async {
    List<String> history = await SearchHistory.getSearchHistory();
    searchHistory.value = history;
  }

  // 清空搜索历史
  Future<void> clearSearchHistory() async {
    await SearchHistory.clearSearchHistory();
    searchHistory.clear();
  }

  // 删除单条搜索历史
  Future<void> removeSearchHistory(String keyword) async {
    await SearchHistory.removeSearchHistory(keyword);
    await loadSearchHistory();
  }

  // 执行搜索
  Future<void> doSearch(String keyword) async {
    if (keyword.trim().isEmpty) return;

    // 收起键盘
    FocusManager.instance.primaryFocus?.unfocus();

    // 保存搜索记录
    await SearchHistory.addSearchHistory(keyword);

    // 重新加载搜索历史
    await loadSearchHistory();

    // 跳转到搜索结果页
    // Get.toNamed(
    //   AppRoutes.searchResult,
    //   arguments: {'keyword': keyword}
    // );
  }

  // 点击搜索历史项
  void onHistoryItemTap(String keyword) {
    searchController.text = keyword;
    doSearch(keyword);
  }

  // 清空搜索框
  void clearSearchInput() {
    searchController.clear();
  }
}
